package top.program.login.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.program.common.utils.MD5Utils;
import top.program.user.entity.User;
import top.program.user.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping
    public String login(){
        return "login";
    }

    /**
      *@Author End_Search
      *@Date 2017/9/17 6:35
      *@Description  校验登录
    */
    @RequestMapping("/check")
    @ResponseBody
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String username = request.getParameter("username");
        String pwd=request.getParameter("password");

        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
//        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SecurityUtils.getSubject().getSession().setTimeout(1800000);
        } catch (Exception e) {
            return "login_fail";
        }
        return "login_succ";



        //调用md5对比代码
        //校验成功//存储session//页面跳转
        //提示错误，返回登录
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//
//        User user = userService.findUserByUserName(username);

//        if(user!=null){
//            String dbPwd = user.getPassword();
//            if(MD5Utils.checkPassword(password,dbPwd)){
//                request.getSession().setAttribute("userinfo",user);
//                return "login_succ";
//            }
//        }
//        return "login_false";
    }
    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        userService.createUser(user);

        return "succ";
    }
}
